<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Validate;
use think\Env;
use app\common\model\Third;
use app\admin\model\air\Plane as PlaneModel;
use app\admin\model\air\PlaneQuote as PlaneQuoteModel;
use app\admin\model\air\Charter as CharterModel;
use app\admin\model\air\CharterQuote as CharterQuoteModel;
use app\admin\model\air\JoinPlane as JoinModel;
use app\admin\model\air\JoinQuote as JoinQuoteModel;
use app\admin\model\air\Custom as CustomModel;
use app\admin\model\air\CustomTravel as TravelModel;
use app\admin\model\air\Forms as FormsModel;
use app\admin\model\air\Setting as SettingModel;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'logout'];
    protected $noNeedRight = '*';
    protected $_user = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->_user = $this->auth->getUser();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $gender = $this->request->post('gender');
        $birthday = $this->request->post('birthday');
        $phone = $this->request->post('phone');
        $avatar = $this->request->post('avatar', '/assets/img/avatar.png', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        if ($phone) {
            $exists = \app\common\model\User::where('mobile', $phone)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('手机已存在'));
            }
            $user->mobile = $phone;
        }
        $user->gender = $gender;
        $user->birthday = $birthday;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    public function saveSaleQuote()
    {
        $planeId = $this->request->post('id');
        $contactor = $this->request->post('contactor');
        $phone = $this->request->post('phone');
        $company = $this->request->post('company');
        $note = $this->request->post('note');
        if (empty($planeId)) {
            $this->error('缺少参数');
        }
        if (empty($contactor) || empty($phone)) {
            $this->error('缺少联系人和电话');
        }
        $plane = PlaneModel::where('status', 'normal')->where('id', $planeId)->find();
        if (!$plane) {
            $this->error('飞机信息不存在');
        }
        $params = [];
        $params['user_id'] = $this->_user->id;
        $params['air_plane_id'] = $planeId;
        $params['contactor'] = $contactor;
        $params['phone'] = $phone;
        $params['company'] = $company;
        $params['note'] = $note;
        PlaneQuoteModel::create($params);
        $res = [];
        $res['qr_img'] = cdnurl(SettingModel::getOneSetting('plane_quote_pic'), true);
        $this->success('询价单信息已提交', $res);
    }

    public function saveCharterQuote()
    {
        $charterId = $this->request->post('charter_id');
        $contactor = $this->request->post('contactor');
        $phone = $this->request->post('phone');
        $company = $this->request->post('company');
        $note = $this->request->post('note');
        $flightDate = $this->request->post('flight_date');
        $startAreaId = $this->request->post('start_area_id');
        $endAreaId = $this->request->post('end_area_id');
        if (empty($charterId)) {
            $this->error('缺少参数');
        }
        if (empty($flightDate)) {
            $this->error('缺少起飞日期');
        }
        if (empty($contactor) || empty($phone)) {
            $this->error('缺少联系人和电话');
        }
        $charter = CharterModel::where('status', 'normal')->where('id', $charterId)->find();
        if (!$charter) {
            $this->error('特惠包机信息不存在');
        }
        $flightDate = date('Y-m-d', strtotime($flightDate));
        if ($flightDate < $charter->start_date || $flightDate > $charter->end_date) {
            $this->error('起飞日期不在特惠包机提供的日期范围内');
        }
        $params = [];
        $params['user_id'] = $this->_user->id;
        $params['air_charter_id'] = $charterId;
        $params['start_area_id'] = $startAreaId;
        $params['end_area_id'] = $endAreaId;
        $params['flight_date'] = $flightDate;
        $params['contactor'] = $contactor;
        $params['phone'] = $phone;
        $params['company'] = $company;
        $params['note'] = $note;
        CharterQuoteModel::create($params);
        $res = [];
        $res['qr_img'] = cdnurl(SettingModel::getOneSetting('charter_quote_pic'), true);
        $this->success('询价单信息已提交', $res);
    }

    public function saveJoinQuote()
    {
        $joinId = $this->request->post('join_id');
        $contactor = $this->request->post('contactor');
        $phone = $this->request->post('phone');
        $company = $this->request->post('company');
        $note = $this->request->post('note');
        $flightDate = $this->request->post('flight_date');
        if (empty($joinId)) {
            $this->error('缺少参数');
        }
        if (empty($flightDate)) {
            $this->error('缺少起飞日期');
        }
        if (empty($contactor) || empty($phone)) {
            $this->error('缺少联系人和电话');
        }
        $join = JoinModel::where('status', 'normal')->where('id', $joinId)->find();
        if (!$join) {
            $this->error('特惠包机信息不存在');
        }
        $flightDate = date('Y-m-d', strtotime($flightDate));
        if ($flightDate < $join->start_date || $flightDate > $join->end_date) {
            $this->error('起飞日期不在拼机提供的日期');
        }
        $params = [];
        $params['user_id'] = $this->_user->id;
        $params['air_join_id'] = $joinId;
        $params['start_area_id'] = $join->start_area_id;
        $params['end_area_id'] = $join->end_area_id;
        $params['flight_date'] = $flightDate;
        $params['contactor'] = $contactor;
        $params['phone'] = $phone;
        $params['company'] = $company;
        $params['note'] = $note;
        JoinQuoteModel::create($params);
        $res = [];
        $res['qr_img'] = cdnurl(SettingModel::getOneSetting('join_quote_pic'), true);
        $this->success('询价单信息已提交', $res);
    }

    public function saveCustomQuote()
    {
        if ($this->request->isPost()) {
            $travelType  = $this->request->post('travel_type');
            $personTotal = $this->request->post('person_total');
            $contactor = $this->request->post('contactor');
            $phone = $this->request->post('phone');
            $note = $this->request->post('note');
            $priceBudget = $this->request->post('price_budget');
            $flexDate = $this->request->post('flex_date');
            $planeLike = $this->request->post('plane_like', '1');
            if (empty($travelType) || empty($personTotal) || empty($contactor)
                || empty($phone) || empty($priceBudget) || empty($flexDate)
            ) {
                $this->error('缺少要提交的表单字段, 请检查');
            }
            // 行程
            // start_date, end_date ,start_area_id, end_area_id
            $travels = $this->request->post('travels/a');
            if (empty($travels)) {
                $this->error('未提交行程, 请检查');
            }
            // 检查有无添加行程
            if ($travelType == '1') {
                $travel = $travels[0];
                if (empty($travel['start_date']) || empty($travel['start_area_id']) || empty($travel['end_area_id'])) {
                    $this->error('行程表单缺少未提交的信息, 请检查');
                }
            }
            if ($travelType == '2') {
                $travel = $travels[0];
                if (empty($travel['start_date']) || empty($travel['end_date']) || empty($travel['start_area_id']) || empty($travel['end_area_id'])) {
                    $this->error('行程表单缺少未提交的信息, 请检查');
                }
            }
            if ($travelType == '3') {
                foreach ($travels as $travel) {
                  if (empty($travel['start_date']) || empty($travel['start_area_id']) || empty($travel['end_area_id'])) {
                      $this->error('多程中有行程表单缺少未提交的信息, 请检查');
                  }
                }
            }
            $params = [];
            $params['user_id'] = $this->_user->id;
            $params['travel_type'] = $travelType;
            $params['person_total'] = $personTotal;
            $params['price_budget'] = $priceBudget;
            $params['flex_date'] = $flexDate;
            $params['plane_like'] = $planeLike;
            $params['contactor'] = $contactor;
            $params['phone'] = $phone;
            $params['note'] = $note;
            $custom = new CustomModel();
            $custom->save($params);
            $customId = $custom->id;
            // 插入行程
            foreach ($travels as $travel) {
                $travel['air_custom_id'] = $customId;
                if (!empty($travel['start_date'])) {
                    $travel['start_date'] = date('Y-m-d', strtotime($travel['start_date']));
                }
                if (!empty($travel['end_date'])) {
                    $travel['end_date'] = date('Y-m-d', strtotime($travel['end_date']));
                }
                if (isset($travel['start_area_name'])) {
                    unset($travel['start_area_name']);
                }
                if (isset($travel['end_area_name'])) {
                    unset($travel['end_area_name']);
                }
                TravelModel::create($travel); 
            }
            $res = [];
            $res['qr_img'] = cdnurl(SettingModel::getOneSetting('custom_quote_pic'), true);
            $this->success('定制信息已提交', $res);

        }
        $this->error('need post request');
    }

    public function getCustoms()
    {
        $data= CustomModel::where('user_id', $this->_user->id)
          ->with(['travels' => function($query) {
              return $query->with(['scity', 'ecity']);
          }])->order('id', 'desc')->order('handle_status', 'desc')->select(); 
        $res = [];
        $types = ['1' => '单程', '2' => '往返', '3' => '多程'];
        $status = ['0'=>'已取消','1'=>'跟进中','2'=>'已有方案'];
        foreach ($data as $d) {
            $travels = $d->travels;
            $ts = [];
            foreach ($travels as $t) {
                if ($d->travel_type == '2') {
                    $ts[] = [
                        'start_area'  => $t->scity->shortname,  
                        'end_area'    => $t->ecity->shortname,
                        'start_date'  => $t->start_date,
                        // 'end_date'    => $t->end_date,
                    ];
                    $ts[] = [
                        'start_area'  => $t->ecity->shortname,  
                        'end_area'    => $t->scity->shortname,
                        'start_date'  => $t->end_date,
                        // 'end_date'    => $t->end_date,
                    ];
                    
                } else {
                    $ts[] = [
                        'start_area'  => $t->scity->shortname,  
                        'end_area'    => $t->ecity->shortname,
                        'start_date'  => $t->start_date,
                        // 'end_date'    => $t->end_date,
                    ];
                }
            }
            $res[] = [
                'id' => $d->id,
                'travel_type' => $types[$d->travel_type],
                'handle_status' => $d->handle_status,
                'handle_status_name' => $status[$d->handle_status],
                'travels' => $ts,
            ];
        }
        $this->success('获取成功', $res);
    }

    public function cancelCustom()
    {
        $id = $this->request->get('id');
        $data = CustomModel::get($id);
        if (!$data) {
            $this->error('未找到对应数据');
        }
        $data->handle_status = 0;
        $data->save();
        $this->success('取消定制成功');
    }

    public function getCustomDetail()
    {
        $id = $this->request->get('id');
        $d = CustomModel::where('id', $id)->where('user_id', $this->_user->id)
          ->with(['travels' => function($query) {
              return $query->with(['scity', 'ecity']);
          }])->find(); 
        if (!$d) {
            $this->error('未找到对应数据');
        }
        $types = ['1' => '单程', '2' => '往返', '3' => '多程'];
        $status = ['0'=>'已取消','1'=>'跟进中','2'=>'已有方案'];
        $flexdates = ['1'=>'±3日','2'=>'±7日','3'=>'±15日'];
        $likes = ['1'=>'不限','2'=>'小型飞机','3'=>'中大型飞机','4'=>'超远程飞机','5'=>'超大型飞机'	];
        $travels = $d->travels;
        $ts = [];
        foreach ($travels as $t) {
            if ($d->travel_type == '2') {
                $ts[] = [
                    'start_area'  => $t->scity->shortname,  
                    'end_area'    => $t->ecity->shortname,
                    'start_date'  => $t->start_date,
                    // 'end_date'    => $t->end_date,
                ];
                $ts[] = [
                    'start_area'  => $t->ecity->shortname,  
                    'end_area'    => $t->scity->shortname,
                    'start_date'  => $t->end_date,
                    // 'end_date'    => $t->end_date,
                ];
                
            } else {
                $ts[] = [
                    'start_area'  => $t->scity->shortname,  
                    'end_area'    => $t->ecity->shortname,
                    'start_date'  => $t->start_date,
                    // 'end_date'    => $t->end_date,
                ];
            }
        }
        $data = [
            'id' => $d->id,
            'travel_type' => $types[$d->travel_type],
            'handle_status' => $d->handle_status,
            'handle_status_name' => $status[$d->handle_status],
            'handle_note' => $d->handle_note,
            'travels' => $ts,
            'person_total' => $d->person_total,
            'price_budget' => '低于' . $d->price_budget .'万',
            'flex_date' => $flexdates[$d->flex_date],
            'plane_like' => $likes[$d->plane_like],
            'contactor' => $d->contactor,
            'phone' => $d->phone,
            'note' => $d->note,
        ];

        $this->success('定制详情成功', $data);
    }

    public function getMyCharters()
    {
        $data= CharterQuoteModel::where('user_id', $this->_user->id)
          ->with(['cc', 'scity', 'ecity'])
          ->order('id', 'desc')->order('quote_status', 'asc')->select(); 
        $res = [];
        $status = ['1'=>'跟进中','2'=>'已处理', '3' => '预定成功', '4' => '已取消'];
        foreach ($data as $d) {
            $res[] = [
                'id' => $d->id,
                'plane_name' => $d->cc->plan_name,
                'flight_date' => date('m月d日', strtotime($d->flight_date)),
                'start_area' => $d->scity->shortname,
                'end_area'   => $d->ecity->shortname,
                'handle_status' => $d->quote_status,
                'handle_status_name' => $status[$d->quote_status],
            ];
        }
        $this->success('获取成功', $res);
    
    }

    public function saveCoop()
    {
        if ($this->request->isPost()) {
            $params = [];
            $formType = 'coop';
            $companyName = $this->request->post('company_name');
            $contactor = $this->request->post('contactor');
            $phone = $this->request->post('phone');
            $email = $this->request->post('email');
            if (empty($contactor) || empty($phone)) {
                $this->error('合作表单请填写联系人和电话');
            }
            $params['form_type'] = $formType;
            $params['company_name'] = $companyName;
            $params['contactor'] = $contactor;
            $params['phone'] = $phone;
            $params['email'] = $email;

            FormsModel::create($params);
            $this->success('提交成功');
        }
    
        $this->error('need post request');
    }

    public function saveFeedback()
    {
        if ($this->request->isPost()) {
            $params = [];
            $formType = 'feedback';
            $feedbackNote = $this->request->post('feedback_note');
            $images = $this->request->post('images/a');
            $phone = $this->request->post('phone');
            if (empty($feedbackNote)) {
                $this->error('反馈表单请反馈内容');
            }
            $params['form_type'] = $formType;
            $params['feedback_note'] = $feedbackNote;
            $params['feedback_images'] = implode(",", $images);
            $params['phone'] = $phone;

            FormsModel::create($params);
            $this->success('提交成功');
        }
    
        $this->error('need post request');
    }


    public function mpWeixinDecodePhone()
    {

        if ($this->request->isPost()) {

            $user = $this->auth->getUser();

            $encryptedData = $this->request->post('encryptedData');
            $iv = $this->request->post('iv');
            $doSet = $this->request->post('doSet', 0); //是否保存

            $mpAppid = Env::get('mp.appid');
            $mpAppSecret = Env::get('mp.app_secret');

            $config = [
                'app_id' => $mpAppid,
                'secret' => $mpAppSecret,

                'response_type' => 'array',
                'log' => [
                    'level' => 'debug',
                    'file' => ROOT_PATH . '/runtime/log/wechat.log',
                ],
            ];

            try {
                $app = Factory::miniProgram($config);

                $sessionkey = Third::where('user_id', $user->id)->find()->sessionkey;

                $decryptedData = $app->encryptor->decryptData($sessionkey, $iv, $encryptedData);

                if ($doSet) {
                    $user->mobile = $decryptedData['phoneNumber'];
                    $user->save();
                }

            } catch (\Exception $e) {

                $this->error($e->getMessage(), null, 401);
            }

            $this->success('ok', ['phone' => $decryptedData['phoneNumber']]);
        }
    }



    //**********************************

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}
